package cloud.pangui.core.utils;

import cloud.pangui.core.exception.UtilsRuntimeException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
 * @Auther hepangui
 * @Date 2020/11/5 0005
 */
public class IOUtils {

	public static final String DEFAULT_CHARSET = "UTF-8";


	/**
	 * 读取为字符串
	 *
	 * @param in
	 * @return
	 */
	public static String readToString(InputStream in) {
		return readToString(in, DEFAULT_CHARSET);
	}

	/**
	 * 读取为字符串
	 *
	 * @param in
	 * @param charset
	 * @return
	 */
	public static String readToString(InputStream in, String charset) {
		try {
			return new String(readToBytes(in), charset);
		} catch (UnsupportedEncodingException e) {
			throw new UtilsRuntimeException(e);
		}
	}

	/**
	 * 读取bytes
	 *
	 * @param in
	 * @return
	 */
	public static byte[] readToBytes(InputStream in) {
		byte[] bytes = new byte[0];
		byte[] data = new byte[1024];
		int read = 0;
		try {
			while ((read = in.read(data)) >= 0) {
				byte[] newArray = new byte[bytes.length + read];
				System.arraycopy(bytes, 0, newArray, 0, bytes.length);
				System.arraycopy(data, 0, newArray, bytes.length, read);
				bytes = newArray;
			}
		} catch (IOException e) {
			throw new UtilsRuntimeException(e);
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				throw new UtilsRuntimeException(e);
			}
		}

		return bytes;
	}

	/**
	 * 写入流
	 *
	 * @param content
	 * @param out
	 */
	public static void writeToStream(String content, OutputStream out) {
		writeToStream(content, out, DEFAULT_CHARSET);
	}

	/**
	 * 写入字符串
	 *
	 * @param content
	 * @param out
	 * @param charset
	 */
	public static void writeToStream(String content, OutputStream out, String charset) {
		try {
			writeToStream(content.getBytes(charset), out);
		} catch (UnsupportedEncodingException e) {
			throw new UtilsRuntimeException(e);
		}
	}

	/**
	 * 写入数据
	 *
	 * @param bytes
	 * @param outputStream
	 */
	public static void writeToStream(byte[] bytes, OutputStream outputStream) {
		try {
			outputStream.write(bytes);
		} catch (IOException e) {
			throw new UtilsRuntimeException(e);
		}finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				throw new UtilsRuntimeException(e);
			}
		}
	}

	/**
	 * 读和写并行
	 *
	 * @param in
	 * @param outputStream
	 */
	public static void readAndWrite(InputStream in, OutputStream outputStream) {
		byte[] data = new byte[1024];
		int read = 0;
		try {
			while ((read = in.read(data)) > 0) {
				outputStream.write(data, 0, read);
			}
		} catch (IOException e) {
			throw new UtilsRuntimeException(e);
		} finally {
			try {
				in.close();
				outputStream.close();
			} catch (IOException e) {
				throw new UtilsRuntimeException(e);
			}
		}
	}
}
